<template>
  <div class="notes-container page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon  @click="goHome"><Notebook /></el-icon>
            笔记管理
          </span>
          <div class="header-actions">
            <el-button
                type="primary"
                @click="showAddDialog = true"
                :icon="Plus"
                class="add-btn"
            >
              添加笔记
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table
            :data="paginatedNotes"
            v-loading="loading"
            style="width: 100%"
            empty-text="暂无笔记"
            :default-sort="{ prop: 'createdAt', order: 'descending' }"
            @sort-change="handleSortChange"
        >
          <el-table-column type="index" width="60" label="序号" align="center" />

          <el-table-column prop="title" label="标题" min-width="200" sortable="custom">
            <template #default="{ row }">
              <div class="title-cell">
                <el-link
                    :href="row.yuqueUrl"
                    target="_blank"
                    type="primary"
                    :underline="false"
                    class="title-link"
                >
                  {{ row.title }}
                </el-link>
                <el-tag v-if="row.folder" size="small" class="folder-tag">
                  {{ row.folder }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createdAt" label="创建时间" width="120" sortable="custom">
            <template #default="{ row }">
              <span class="time-text">{{ formatDate(row.createdAt) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="复习计划" min-width="250">
            <template #default="{ row }">
              <div class="review-schedules">
                <el-tag
                    v-for="schedule in row.reviewSchedules"
                    :key="schedule.stage"
                    :type="schedule.completed ? 'success' : 'primary'"
                    size="small"
                    class="schedule-tag"
                    :title="getScheduleTitle(schedule)"
                >
                  第{{ schedule.stage }}次
                  <el-icon v-if="schedule.completed" class="check-icon">
                    <Check />
                  </el-icon>
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="复习进度" width="100" align="center">
            <template #default="{ row }">
              <el-progress
                  :percentage="calculateReviewProgress(row.reviewSchedules)"
                  :stroke-width="8"
                  :show-text="false"
              />
              <span class="progress-text">
                {{ calculateReviewProgress(row.reviewSchedules) }}%
              </span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                  type="success"
                  size="small"
                  @click="handleUpdateClick(row)"
                  :icon="Update"
                  class="update-btn"
              >
                修改
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(row.id)"
                  :icon="Delete"
                  class="delete-btn"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[5 ,10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination"
        />
      </div>
    </el-card>

    <!-- 添加笔记对话框 -->
    <add-note-dialog
        v-model="showAddDialog"
        @success="handleNoteAdded"
    />

    <!-- 修改笔记对话框 -->
    <!-- 在 template 部分修改 UpdateNoteDialog 的调用 -->
    <update-note-dialog
        v-model="showUpdateDialog"
        :note-id="selectedNoteId"
        @success="handleNoteUpdated"
    />
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddNoteDialog from '@/components/AddNoteDialog.vue'
import UpdateNoteDialog from '@/components/UpdateNoteDialog.vue'
import { getNotes, deleteNote } from '@/api/notes'
import dayjs from 'dayjs'
import {useRouter} from "vue-router";
import { inject } from 'vue'

export default {
  name: 'NotesView',
  components: {
    AddNoteDialog,
    UpdateNoteDialog
  },
  setup() {
    // 注入全局刷新函数
    const refreshAllData = inject('refreshAllData')
    const selectedNoteId = ref(null) // 添加选中的笔记ID
    const router = useRouter()
    const notes = ref([])
    const loading = ref(false)
    const showAddDialog = ref(false)
    const showUpdateDialog = ref(false)
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = computed(() => notes.value.length)

    // 排序相关
    const sortProp = ref('createdAt')
    const sortOrder = ref('descending')

    // 分页后的笔记数据
    const paginatedNotes = computed(() => {
      let sortedNotes = [...notes.value]

      // 排序
      if (sortProp.value) {
        sortedNotes.sort((a, b) => {
          let aVal = a[sortProp.value]
          let bVal = b[sortProp.value]

          if (sortProp.value === 'createdAt') {
            aVal = new Date(aVal).getTime()
            bVal = new Date(bVal).getTime()
          }

          if (sortOrder.value === 'ascending') {
            return aVal > bVal ? 1 : -1
          } else {
            return aVal < bVal ? 1 : -1
          }
        })
      }

      // 分页
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return sortedNotes.slice(start, end)
    })

    // 加载笔记列表
    const loadNotes = async () => {
      loading.value = true
      try {
        const response = await getNotes()

        if (response.success) {
          notes.value = response.data
        }
      } catch (error) {
        ElMessage.error('加载笔记失败')
      } finally {
        loading.value = false
      }
    }

    // 删除笔记
    // 在删除笔记成功后调用全局刷新
    const handleDelete = async (noteId) => {
      try {
        await ElMessageBox.confirm(
            '确定要删除这条笔记吗？此操作不可恢复。',
            '警告',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              confirmButtonClass: 'el-button--danger'
            }
        )

        const response = await deleteNote(noteId)
        if (response.success) {
          ElMessage.success('删除成功')
          await loadNotes()
          // 调用全局刷新，确保首页数据同步
          if (refreshAllData) {
            await refreshAllData()
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    // 在添加笔记成功后也调用全局刷新
    const handleNoteAdded = () => {
      loadNotes()
      showAddDialog.value = false
      // 调用全局刷新，确保首页数据同步
      if (refreshAllData) {
        refreshAllData()
      }
    }
    //修改 成功后全局刷新
    const handleNoteUpdateed = () => {
      loadNotes()
      showUpdateDialog.value = false
      // 调用全局刷新，确保首页数据同步
      if (refreshAllData) {
        refreshAllData()
      }
    }
    // 修改按钮点击事件
    const handleUpdateClick = (row) => {
      selectedNoteId.value = row.id
      showUpdateDialog.value = true
    }
    // 回到主页
    const goHome = () => {
      router.push("/")
    }

    // 处理分页大小变化
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      currentPage.value = 1
    }

    // 处理当前页变化
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
    }

    // 处理排序变化
    const handleSortChange = ({ prop, order }) => {
      sortProp.value = prop
      sortOrder.value = order
    }

    // 格式化日期
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }

    // 计算复习进度
    const calculateReviewProgress = (schedules) => {
      if (!schedules || schedules.length === 0) return 0
      const completed = schedules.filter(s => s.completed).length
      return Math.round((completed / schedules.length) * 100)
    }

    // 获取复习计划标题
    const getScheduleTitle = (schedule) => {
      const date = dayjs(schedule.scheduledDate).format('YYYY-MM-DD')
      return `第${schedule.stage}次复习 - ${date} ${schedule.completed ? '(已完成)' : '(待完成)'}`
    }

    onMounted(() => {
      loadNotes()
    })

    return {
      notes,
      loading,
      showAddDialog,
      showUpdateDialog,
      currentPage,
      pageSize,
      total,
      paginatedNotes,
      handleDelete,
      handleNoteAdded,
      handleNoteUpdateed,
      selectedNoteId,
      handleUpdateClick,
      handleSizeChange,
      handleCurrentChange,
      handleSortChange,
      formatDate,
      calculateReviewProgress,
      getScheduleTitle,
      goHome
    }
  }
}
</script>

<style lang="scss" scoped>
.notes-container {
  padding: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.table-container {
  min-height: 400px;
}

.el-table {
  min-width: 800px;
}
.title-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title-link {
  font-weight: 500;
  line-height: 1.4;
}

.folder-tag {
  align-self: flex-start;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.time-text {
  color: #606266;
  font-size: 13px;
}

.review-schedules {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.schedule-tag {
  margin: 1px;
  cursor: default;
}

.check-icon {
  margin-left: 2px;
}

.progress-text {
  display: block;
  text-align: center;
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.delete-btn {
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: center;
}

.pagination {
  margin-top: 20px;
}

// 响应式设计
@media (max-width: 768px) {
  .notes-container {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;

    .add-btn {
      width: 100%;
    }
  }

  .review-schedules {
    justify-content: center;
  }

  .pagination-container {
    overflow-x: auto;
  }
}
</style>